package com.qianfeng.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;

/**
 * 2019/12/7
 * Administrator
 * springboot1207
 * 面向对象面向君  不负代码不负卿
 */
//配置第一个数据源
    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(
            entityManagerFactoryRef = "entityManagerFactoryBeanB",
            transactionManagerRef = "txB",
            basePackages = {"com.qianfeng.hunan.dao"}
    )
public class JpaConfigTwo {
    //1.指定数据源
    @Resource(name="twodatasource")
    private DataSource dataSource;
    @Autowired  //该对象是底层自动绑定
    private JpaProperties jpaProperties;

    //得到JpaProperties信息（自定义方法）
    private Map<String ,String> getProperties(DataSource dataSource){
        return  jpaProperties.getHibernateProperties(dataSource);
    }
    //2.创建LocalContainerEneityManagerFactoryBean
    @Bean(name="entityManagerFactoryBeanB")
    public LocalContainerEntityManagerFactoryBean aa(EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean build = builder.dataSource(dataSource)
                .properties(getProperties(dataSource))//指定JPAProperties
                .packages("com.qianfeng.hunan.bean")//指定PackageToScan
                .persistenceUnit("twounit")
                .build();
        return build;
    }
    //3.事务
    @Bean(name="txB")
    public PlatformTransactionManager tx(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(aa(builder).getObject());
    }
    //得到EntityManager对象
  /*  public EntityManager entityManager(EntityManagerFactoryBuilder builder){
        return aa(builder).getObject().createEntityManager();
    }*/


}
